<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Location
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

bx_import('BxDolTwigPageMain');
bx_import('BxTemplCategories');

class BxLocationPageMain extends BxDolTwigPageMain {

    function BxLocationPageMain(&$oMain) {

		$this->oDb = $oMain->_oDb;
        $this->oConfig = $oMain->_oConfig;
		$this->oMain = $oMain;

        $this->sSearchResultClassName = 'BxLocationSearchResult';
        $this->sFilterName = 'modzzz_location_filter';
		parent::BxDolTwigPageMain('modzzz_location_main', $oMain);
	}
  
    function getBlockCode_Map() {
 
 		$sMeasurementType = getParam('modzzz_location_measurement_type'); 
		$sBaseUri = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri();

		$iProfileId = getLoggedId();
        $aViewer = getProfileInfo($iProfileId);

		if($iProfileId){
 			$this->oTemplate->addInjection('injection_body', 'text',  'onload="load();searchLocations(\''.$sBaseUri.'\');"');
		}else{
 			$this->oTemplate->addInjection('injection_body', 'text',  'onload="load();"');
		}

		$this->oTemplate->addJs ('http://maps.google.com/maps/api/js?sensor=false');
 		$this->oTemplate->addJs ('gmap_multiple.js');
  
		switch($sMeasurementType){
			case 'miles':
				$sMeasurementTypeC = _t('_modzzz_location_miles');
			break;
			case 'kilometers':
				$sMeasurementTypeC = _t('_modzzz_location_kilometers');
			break;
			default:
				$sMeasurementTypeC = _t('_modzzz_location_kilometers');
			break;
		}
 
		$aVars = array (  
			'city_country' => (trim($aViewer['City'])) ? trim($aViewer['City']) .','. $aViewer['Country'] : '',
			'zoom' => getParam('modzzz_location_map_zoom'),
			'lat' => getParam('modzzz_location_map_lat'),
			'long' => getParam('modzzz_location_map_long'),
			'distance' => (int)getParam('modzzz_location_map_default_distance'), 
			'distance_type' => $sMeasurementTypeC,
			'base_uri' => $sBaseUri 
		);
 
        return $this->oTemplate->parseHtmlByName('block_map_multiple', $aVars);
	} 

    function getBlockCode_LocationCategories() {
  
	    $aAllEntries = $this->oDb->getCategoryInfo(0, true);
     
        $aResult['bx_repeat:entries'] = array();        
 		foreach($aAllEntries as $aEntry)
		{	 
			$iNumCategory = $this->oDb->getParentCategoryCount($aEntry['id']);	 
			$sCatHref = $this->oDb->getCategoryUrl($aEntry['uri']);  
			$sCategory = $aEntry['name'];
 
	        $aResult['bx_repeat:entries'][] = array(
                'cat_url' => $sCatHref, 
                'cat_name' => $sCategory,
			    'num_items' => $iNumCategory, 
            );	        
	    } 
 
	    return $this->oTemplate->parseHtmlByName('location_categories', $aResult);  
	}
  
    function getBlockCode_LatestFeaturedLocation() {
 
	    return $this->ajaxBrowse('featured', 1); 
    }
 
    function getBlockCode_Recent() { 
        return $this->ajaxBrowse('recent', $this->oDb->getParam('modzzz_location_perpage_main_recent'));
    }

	function getBlockCode_Popular() { 
        return $this->ajaxBrowse('popular', $this->oDb->getParam('modzzz_location_perpage_main_recent'));
    }
    
	function getBlockCode_Top() { 
        return $this->ajaxBrowse('top', $this->oDb->getParam('modzzz_location_perpage_main_recent'));
    }

	function getLocationMain() {
        return BxDolModule::getInstance('BxLocationModule');
    }


	function getBlockCode_Search() {
   
        $this->oTemplate->pageStart();
 
        bx_import('BxDolCategories');
        bx_import('BxDolProfileFields'); 
  
        $oProfileFields = new BxDolProfileFields(0);
        $aCountries = $oProfileFields->convertValues4Input('#!Country');
		$aCountries[''] = "";  
		asort($aCountries);
		$aProfile = getProfileInfo((int)$iProfileId);
		$sDefaultCountry = $aProfile['Country'];
   		$aStates = $this->oDb->getStateArray($sDefaultCountry);  

		$sStateUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() . 'home/?ajax=state&country=' ;
 
		$sCatUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() . 'home/?ajax=cat&parent=' ;

		$aCategories = $this->oDb->getFormCategoryArray();
 
        $aForm = array(

            'form_attrs' => array(
                'name'     => 'form_search_location',
                'action'   => '',
                'method'   => 'post',
            ),      

            'params' => array (
                'db' => array(
                    'submit_name' => 'submit_form',
                ),
            ),
                  
            'inputs' => array(
                'Keyword' => array(
                    'type' => 'text',
                    'name' => 'Keyword',
                    'caption' => _t('_modzzz_location_form_caption_keyword'),
                    'required' => false, 
                    'db' => array (
                        'pass' => 'Xss', 
                    ),
                ),                
                'parent' => array(
                    'type' => 'select',
                    'name' => 'parent',
					'values'=> $aCategories,
                    'caption' => _t('_modzzz_location_parent_categories'),
					'attrs' => array(
						'onchange' => "getHtmlData('subcat','$sCatUrl'+this.value)",
                        'id' => 'parentcat',
					),
                    'required' => false, 
                ), 
                'Category' => array(
                    'type' => 'select',
                    'name' => 'Category',
					'values'=> array(),
                    'caption' => _t('_Categories'),
					'attrs' => array(
                        'id' => 'subcat',
					),
                    'required' => false, 
                    'db' => array (
                        'pass' => 'Int', 
                    ),
                ),
                'Country' => array(
					'type' => 'select',
                    'name' => 'Country',
                    'caption' => _t('_modzzz_location_form_caption_country'),
                    'values' => $aCountries,
					'attrs' => array(
						'onchange' => "getHtmlData('substate','$sStateUrl'+this.value)",
					), 
					'value' => $sDefaultCountry, 
                    'required' => false, 
                    'db' => array (
                        'pass' => 'Preg', 
                        'params' => array('/([a-zA-Z]{0,2})/'),
                    ),  
                ),
				'State' => array(
					'type' => 'select',
					'name' => 'State', 
					'caption' => _t('_modzzz_location_form_caption_state'),
					'values'=> $aStates,  
					'attrs' => array(
						'id' => 'substate',
					), 
				    'db' => array (
						'pass' => 'Preg', 
						'params' => array('/([a-zA-Z]+)/'),
					), 
				), 
                'City' => array(
                    'type' => 'text',
                    'name' => 'City',
                    'caption' => _t('_modzzz_location_form_caption_city'),
                    'required' => false,  
                    'db' => array (
                        'pass' => 'Xss', 
                    ),
                    'display' => true,
                ),    
                'Submit' => array (
                    'type' => 'submit',
                    'name' => 'submit_form',
                    'value' => _t('_modzzz_location_continue'),
                    'colspan' => true,
                ),
            ),            
        );


 
        $oForm = new BxTemplFormView($aForm);
        $oForm->initChecker(); 
  
        if ($oForm->isSubmittedAndValid ()) {
 
            modzzz_location_import ('SearchResult');
            $o = new BxLocationSearchResult('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('City'), $oForm->getCleanValue('State'), $oForm->getCleanValue('Country') );
 
            if ($o->isError) {
                $this->oTemplate->displayPageNotFound ();
                exit;
            }

            if ($s = $o->processing()) {
                echo $s;
            } else {
                $this->oTemplate->displayNoData ();
                exit;
            }

            $this->oMain->isAllowedSearch(true); // perform search action 

            $this->oTemplate->addCss ('unit.css');
            $this->oTemplate->addCss ('main.css');
            $this->oTemplate->pageCode($o->aCurrent['title'], false, false);
			exit;

        } 
 
        return $oForm->getCode(); 
    } 
  
    function ajaxBrowseSubProfile($sType, $sMode, $iPerPage, $aMenu = array(), $sValue = '', $isDisableRss = false, $isPublicOnly = true) {

        bx_import ('SearchResult', $this->oMain->_aModule);
        $sClassName = $this->sSearchResultClassName;
        $o = new $sClassName($sMode, $sValue);
        $o->aCurrent['paginate']['perPage'] = $iPerPage; 
        $o->setPublicUnitsOnly($isPublicOnly);

        if (!$aMenu)
            $aMenu = ($isDisableRss ? '' : array(_t('RSS') => array('href' => $o->aCurrent['rss']['link'] . (false === strpos($o->aCurrent['rss']['link'], '?') ? '?' : '&') . 'rss=1', 'icon' => getTemplateIcon('rss.png'))));

        if ($o->isError)
            return array(MsgBox(_t('_Error Occured')), $aMenu);

        if (!($s = $o->displaySubProfileResultBlock($sType))) 
            return $isPublicOnly ? array(MsgBox(_t('_Empty')), $aMenu) : '';


        $sFilter = (false !== bx_get($this->sFilterName)) ? $this->sFilterName . '=' . bx_get($this->sFilterName) . '&' : '';
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $o->aCurrent['paginate']['totalNum'],
            'per_page' => $o->aCurrent['paginate']['perPage'],
            'page' => $o->aCurrent['paginate']['page'],
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $this->sUrlStart . $sFilter . 'page={page}&per_page={per_page}\');',
        ));
        $sAjaxPaginate = $oPaginate->getSimplePaginate($this->oConfig->getBaseUri() . $o->sBrowseUrl);

        return array(
            $s, 
            $aMenu,
            $sAjaxPaginate,
            '');
    }    

    function getBlockCode_Tags($iBlockId) { 
        bx_import('BxTemplTagsModule');
        $aParam = array(
            'type' => 'modzzz_location',
            'orderby' => 'popular',
			'pagination' => getParam('tags_perpage_browse')
        );

		$sUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() . 'tags';
  
        $oTags = new BxTemplTags();
        $oTags->getTagObjectConfig();
    
        return array(
            $oTags->display($aParam, $iBlockId, '', $sUrl),
            array(),
            array(),
            _t('_Tags')
        ); 

    }
 
	function getBlockCode_Reviews() { 
 
		$iLimit = $this->oDb->getParam('modzzz_location_perpage_review');
		 
		$iCount = $this->oDb->getReviewCount(0);  

		if(!$iCount)
			return;
 
		$sqlLimit = "LIMIT 0, {$iLimit}";  

		$aAllEntries = $this->oDb->getReviews(0, $sqlLimit);
 
		$aVars = array (
			'bx_repeat:review' => array (),
		);
  
		foreach($aAllEntries as $aEntry)
		{ 
 
			$iEntryId = $aEntry['id']; 
			$iLocationId = $aEntry['location_id']; 
 			$iSubId = (int)$aEntry['sub_id'];

			$sType = $aEntry['type'];
			if($sType=='location'){
				$aLocation = $this->oDb->getEntryById($iLocationId);
				
				$sLocationName = $aLocation['title'];
				$sLocationUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() . 'view/' . $aLocation['uri'];
			}else{
				$aSubProfile = $this->oDb->getSubProfileEntryById($sType, $iSubId);
				$aLocation = $this->oDb->getEntryById($iLocationId);
				
				$sLocationName = $aSubProfile['title'];
				$sLocationUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() . $sType .'/view/' . $aSubProfile['uri'];
			}
   
			$iMemberId = $aEntry['member_id'];
			$sNickName = getNickName($iMemberId);
			$sNickLink = getProfileLink($iMemberId);
			$icoMember = get_member_thumbnail($iMemberId, 'left');
			$sMessage = $aEntry['desc']; 
			$dtSent = date("M jS, Y", $aEntry['created']);
 
			$aVars['bx_repeat:review'][] = array (
				'entry_id' => $iLocationId, 
				'review_id' => $iEntryId, 
				'ico_member' => $icoMember, 
				'nicklink' => $sNickLink,
				'nickname' => $sNickName,
				'date' => $dtSent,
				'message' => $sMessage,
				'location_name' => $sLocationName, 
				'location_url' => $sLocationUrl, 
				'location' => $this->oDb->getLocationIdentifier($sType),  
			);  
		} 
  
		$sCode = $this->oTemplate->parseHtmlByName('location_reviews', $aVars);
	 
		return $sCode; 
 	}
 
	function getBlockCode_Forum() {
  		
		$aPosts = $this->oDb->getAll("SELECT e.`title`, e.`thumb`, e.`author_id`,
		f.`forum_uri`, p.`user`, p.`post_text`, t.`topic_uri`, t.`topic_title`,p.`when` FROM `modzzz_location_forum` f, `modzzz_location_forum_topic` t, `modzzz_location_forum_post` p, `modzzz_location_main` e WHERE p.`topic_id`=t.`topic_id` AND t.`forum_id`=f.`forum_id` AND e.`ID`=f.`entry_id` ORDER BY  p.`when`");
 		 
		if(!count($aPosts))
			return;

		$aVars['bx_repeat:entries'] = array();
  		foreach($aPosts as $aEachPost){

			$sForumUri = $aEachPost['forum_uri'];
			$sTopic = $aEachPost['topic_title']; 
			$sTopicUri = $aEachPost['topic_uri'];
			$sPostText = $aEachPost['post_text']; 
			$sDate = defineTimeInterval($aEachPost['when']); 
			$sLocationName = $aEachPost['title']; 
 			$sPoster = $aEachPost['user']; 
 
			if($aEachPost['thumb']){
				$a = array ('ID' => $aEachPost['author_id'], 'Avatar' => $aEachPost['thumb']); 
				$aImage = BxDolService::call('photos', 'get_image', array($a, 'thumb'), 'Search'); 
				$sImage = $aImage['no_image'] ? '' : $aImage['file'];
			}
 
			$iLimitChars = (int)getParam('modzzz_location_forum_max_preview');
			if (strlen($sPostText) > $iLimitChars) {
				$sLinkMore = '...';
				$sPostText = process_line_output(mb_substr(strip_tags($sPostText), 0, $iLimitChars)) . $sLinkMore;
			}


			$sLocationUrl = BX_DOL_URL_ROOT . $this->oConfig->getBaseUri() .'view/' . $sForumUri;
			$sTopicUrl = BX_DOL_URL_ROOT . 'forum/location/forum/'.$sForumUri.'-0.htm#topic/'.$sTopicUri.'.htm';
	
			$aVars['bx_repeat:entries'][] = array( 
							'topic_url' => $sTopicUrl, 
							'topic' => $sTopic, 
							'post' => $sPostText, 
							'location_name' => $sLocationName, 
							'location_url' => $sLocationUrl, 
							'post_date' => $sDate,
							'nicklink' => getProfileLink(getID($sPoster)),
							'nickname' => $sPoster,
							'thumb' => ($sImage) ? $sImage : $this->oTemplate->getIconUrl('no-photo.png'),
						);
		}

		$sCode = $this->oTemplate->parseHtmlByName('location_forum', $aVars);  

		return $sCode;
	}


}

?>
